package com.chinastock.log;

import com.chinastock.communication.BaseResponse;
import com.chinastock.model.EcpMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wangzhendong
 */
@ConditionalOnProperty(prefix = "web.log",value = "enabled",matchIfMissing = true)
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param ex 异常体 Exception
     * @return
     */
    Logger logger = LoggerFactory.getLogger(LogName.ECP);

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseResponse<Void> errorHandler(Exception ex) {
        EcpMessage message = new EcpMessage();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        message.setUrl(request.getRequestURL().toString());
        message.setException(ex);
        logger.error(message.toString());
        BaseResponse response = new BaseResponse<Void>(false, "501", "后台服务异常");
        return response;
    }

}